﻿using System;
using System.Windows;
using System.Windows.Input;

namespace Mandarine.Controls.ApplicationBar
{
    /// <summary>
    /// アプリケーションバーアイテムとバインドするためのコマンドクラス
    /// </summary>
    public class AppBarItemCommand : AppBarItemBehavior
    {
        #region dependency properties

        /// <summary>
        /// 依存プロパティ Command
        /// </summary>
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command"
            , typeof(ICommand)
            , typeof(AppBarItemCommand)
            , new PropertyMetadata((s, e) =>
            {
                //コマンド変更時
                var c = (AppBarItemCommand) s;
                var oldCommand = e.OldValue as ICommand;
                if (oldCommand != null)
                {
                    oldCommand.CanExecuteChanged -= c.CanExecuteChanged;
                }

                var newCommand = e.NewValue as ICommand;
                if (newCommand != null)
                {
                    newCommand.CanExecuteChanged += c.CanExecuteChanged;
                    c.ChangeIsEnabled();
                }
            }));
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        /// <summary>
        /// 依存プロパティ CommandParameter
        /// </summary>
        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.Register("CommandParameter"
            , typeof(object)
            , typeof(AppBarItemCommand), null);

        public object CommandParameter
        {
            get { return (object)GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }

        #endregion


        protected override void OnDetaching()
        {
            if (Command != null)
            {
                Command.CanExecuteChanged -= CanExecuteChanged;
            }

            base.OnDetaching();
        }

        protected override void OnItemClick()
        {
            if (Command != null && Command.CanExecute(CommandParameter))
            {
                Command.Execute(CommandParameter);
            }
        }

        /// <summary>
        /// コマンドCanExecuteChangedイベント発火時にアプリケーションバーアイテムのIsEnabledを上書きする
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CanExecuteChanged(object sender, EventArgs e)
        {
            ChangeIsEnabled();
        }
        /// <summary>
        /// アプリケーションバーアイテムのIsEnabledプロパティを自身のコマンドで変更します
        /// </summary>
        private void ChangeIsEnabled()
        {
            _item.IsEnabled = Command.CanExecute(CommandParameter);
        }

    }
}
